part of 'index.dart';

class FriendPage extends StatefulWidget {
  const FriendPage({super.key});

  @override
  State<FriendPage> createState() => _FriendPageState();
}

class _FriendPageState extends State<FriendPage>
    with SingleTickerProviderStateMixin {
  late final _tabController = TabController(length: 3, vsync: this);
  final currentIndex = ValueNotifier(0);
  bool empty = false;

  @override
  initState() {
    super.initState();
    _tabController.addListener(() {
      currentIndex.value = _tabController.index;
    });
    FriendAPI.friendList(pageNum: 1, pageSize: 1).then((value) {
      if (mounted) setState(() => empty = value.isEmpty);
    });
  }

  Widget _buildTab(int index, String label) {
    final active = currentIndex.value == index;
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 3),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(99),
        color: active ? Colors.white : const Color(0xFFF4F4F4),
        border: Border.all(
          color: active ? const Color(0xFF8A72FE) : Colors.transparent,
          width: 1,
        ),
      ),
      child: Text(label),
    );
  }

  Widget _buildEmpty() {
    return Positioned(
      top: 0,
      left: 15,
      right: 15,
      child: Container(
        padding: const EdgeInsets.symmetric(
          horizontal: 10,
          vertical: 20,
        ),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(10),
          boxShadow: [
            BoxShadow(
              color: const Color(0xFF787878).withOpacity(0.1),
              spreadRadius: 1,
              blurRadius: 5,
              offset: const Offset(4, 0),
            )
          ],
        ),
        child: Row(
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                FittedBox(
                  child: Text(
                    T.current.chat2_no_friend,
                    style: const TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 18,
                    ),
                  ),
                ),
                FittedBox(
                  child: Text(
                    T.current.chat2_start_online,
                    style: const TextStyle(
                      color: Color(0xFFC1C1C1),
                      fontSize: 12,
                    ),
                  ),
                ),
              ],
            ).expanded,
            Container(
              margin: EdgeInsets.only(
                left: Tools.isAr ? 0 : 10,
                right: Tools.isAr ? 10 : 0,
              ),
              padding: const EdgeInsets.symmetric(
                horizontal: 12,
                vertical: 2,
              ),
              decoration: BoxDecoration(
                color: const Color(0xFF8A72FE),
                borderRadius: BorderRadius.circular(99),
              ),
              child: Text(
                T.current.chat6_got,
                style: const TextStyle(
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
            ).onTap(() {
              Get.to(() => const FriendSearchPage());
            }),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          clipBehavior: Clip.hardEdge,
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 0),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(20),
          ),
          child: Column(
            children: [
              Padding(
                padding:
                    EdgeInsets.only(top: empty ? 100 : 20, left: 12, right: 12),
                child: ValueListenableBuilder(
                  valueListenable: currentIndex,
                  builder: (context, index, child) {
                    return TabBar(
                      controller: _tabController,
                      isScrollable: true,
                      dividerColor: Colors.transparent,
                      tabAlignment: TabAlignment.start,
                      indicatorSize: TabBarIndicatorSize.label,
                      indicatorWeight: 1,
                      onTap: (index) => currentIndex.value = index,
                      indicator: const BoxDecoration(color: Colors.transparent),
                      overlayColor:
                          const WidgetStatePropertyAll(Colors.transparent),
                      padding: EdgeInsets.zero,
                      labelPadding: const EdgeInsets.only(right: 10),
                      unselectedLabelStyle: const TextStyle(
                          color: Color(0xFFC1C1C1), fontSize: 12),
                      labelStyle: const TextStyle(
                          color: Color(0xFF8A72FE), fontSize: 12),
                      tabs: [
                        _buildTab(0, T.current.c_friend),
                        _buildTab(1, T.current.chat5_following),
                        _buildTab(2, T.current.me_followers),
                      ],
                    );
                  },
                ),
              ),
              Expanded(
                child: TabBarView(
                  physics: const NeverScrollableScrollPhysics(),
                  controller: _tabController,
                  children: [
                    UserView(FriendType.friend),
                    UserView(FriendType.following),
                    UserView(FriendType.followed),
                  ],
                ),
              ),
            ],
          ),
        ),
        if (empty) _buildEmpty(),
      ],
    );
  }
}

class UserView extends StatelessWidget {
  const UserView(this.type, {super.key});
  final FriendType type;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 15),
      child: GetBuilder<FriendController>(
        init: FriendController(type),
        tag: type.toString(),
        builder: (controller) => CustomPullScrollView(
          controller: controller.refreshController,
          onLoading: controller.onLoading,
          onRefresh: controller.onRefresh,
          refreshOnStart: false,
          builder: (context, physics) => CustomScrollView(
            physics: physics,
            slivers: [
              if (controller.list.isEmpty)
                Padding(
                  padding: const EdgeInsets.only(top: 200),
                  child: Image.asset(
                    Images.bgPlaceEmpty,
                    width: 200,
                    height: 200,
                  ),
                ).sliver,
              SliverList.separated(
                itemBuilder: (context, index) {
                  return _Card(controller.list[index]);
                },
                separatorBuilder: (context, index) => Divider(
                  height: 0,
                  thickness: 0.5,
                  color: const Color(0xFFD8D8D8).withOpacity(0.5),
                ),
                itemCount: controller.list.length,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _Card extends StatelessWidget {
  const _Card(this.model);
  final FriendModel model;

  void _onTap() {
    final conversation = EMConversation.fromJson({
      'convId': model.imId,
      'type': 0,
    });
    final user = chat.UserInfo.fromJson({
      'userId': ImManager.customerId,
      'nickName': model.nickname ?? '',
      'avatarUrl': model.headPortraitsUrl ?? Constants.avatar,
    });
    Get.to(() => ChatPage(conversation: conversation, user: user));
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 12),
      child: Row(
        children: [
          image(
            model.headPortraitsUrl ?? Constants.avatar,
            width: 50,
            height: 50,
            fit: BoxFit.cover,
          ).clipRRect(99).onTap(() {
            final sp = model.imId?.split('_');
            if (sp?.isNotEmpty == true) {
              Get.to(() => UserDetailsPage(userId: sp!.first));
            }
          }),
          const SizedBox(width: 8),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                model.nickname ?? '',
                style: const TextStyle(
                  fontSize: 15,
                  fontWeight: FontWeight.w500,
                ),
              ),
              const SizedBox(height: 3),
              Text(
                model.personalSignature ?? '',
                style: const TextStyle(
                  color: Color(0xFFC1C1C1),
                  fontSize: 12,
                ),
              ),
            ],
          ).expanded,
          Transform.flip(
            flipX: Tools.isAr,
            child: Image.asset(Images.icChatHi, width: 32, height: 32),
          )
        ],
      ),
    ).onTap(_onTap);
  }
}
